package com.music.checkpoints.common.amqp.receiver;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.music.checkpoints.common.amqp.AmqpExchange;
import com.music.checkpoints.common.amqp.event.SubmitAnswerEvent;
import com.music.checkpoints.common.vo.DetailVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class SubmitAnswerReceiver {
    @Autowired(required = false)
    private List<SubmitAnswerEvent> events;

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = AmqpExchange.SUBMIT_ANSWER + "_QUEUE"),
            exchange = @Exchange(value = AmqpExchange.SUBMIT_ANSWER, type = ExchangeTypes.FANOUT)
    ))
    public void submitAnswer(String jsonString) {
        if (events != null) {
            for (SubmitAnswerEvent event : events) {
                try {
                    JSONObject jo = JSON.parseObject(jsonString);
                    DetailVO detailVO = JSONObject.toJavaObject(jo, DetailVO.class);
                    event.submitAnswer(detailVO);
                } catch (Exception e) {
                    logger.error("|===submitAnswer===| error: {}", e.getMessage());
                }
            }
        }
    }
}
